from django.db import migrations
from django.conf import settings
from django.contrib.auth import get_user_model

def create_test_user(apps, schema_editor):
    """创建测试用户"""
    User = get_user_model()
    config = settings.TEST_USER_CONFIG
    
    if not config.get('AUTO_CREATE', True):
        return
    
    # 检查用户是否已存在
    if not User.objects.filter(username=config['USERNAME']).exists():
        try:
            user = User.objects.create_user(
                username=config['USERNAME'],
                email=config['EMAIL'],
                password=config['PASSWORD'],
                platform='web',
                is_active=True,
                is_staff=False  # 不是管理员
            )
            print(f"✅ 已创建测试用户: {config['USERNAME']}")
            print(f"📧 邮箱: {config['EMAIL']}")
            print(f"🔑 密码: {config['PASSWORD']}")
        except Exception as e:
            print(f"❌ 创建测试用户失败: {e}")

def delete_test_user(apps, schema_editor):
    """删除测试用户（回滚操作）"""
    User = get_user_model()
    config = settings.TEST_USER_CONFIG
    
    try:
        user = User.objects.get(username=config['USERNAME'])
        user.delete()
        print(f"已删除测试用户: {config['USERNAME']}")
    except User.DoesNotExist:
        pass

class Migration(migrations.Migration):

    dependencies = [
        ('account', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(create_test_user, delete_test_user),
    ]